package com.hhs.storage.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.hhs.storage.bean.*;
import com.hhs.storage.bean.person.config.PersonPlanUndoNotifyConfig;
import com.hhs.storage.dao.PersonConfigTitleDao;
import com.hhs.storage.service.PersonConfigTitleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hhs.storage.util.DateEasy;
import com.hhs.storage.util.SysUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author chx
 * @since 2024-05-15
 */
@Service
@Slf4j
public class PersonConfigTitleServiceImpl extends ServiceImpl<PersonConfigTitleDao, PersonConfigTitle> implements PersonConfigTitleService {
    @Resource
    private HttpServletRequest request;

    /**
     * 更新-个人计划未执行通知设置
     *
     * @param userId
     * @param open
     * @param time
     * @return
     */
    @Override
    public Map editPersonPlanTitleConfig(String userId, Boolean open, Integer time, LocalDateTime nomtime, String planId) {
        if (open == false) {
            return ResponseInfo.error("未开启标题提醒");
        }

        if (time <= 0) {
            return ResponseInfo.error("时间间隔必须大于0");
        }

        //获取用户id
        userId = getUserId(userId);
        //参数设置
        PersonPlanUndoNotifyConfig json = new PersonPlanUndoNotifyConfig();
        json.setOpen(open);
        json.setTime(time);
        if (nomtime == null) {
            json.setNomtime(LocalDateTime.now());
        } else {
            DateEasy da=new DateEasy(nomtime);
            da.addSecond(-time);
            json.setNomtime(da.toLocalDateTime());
        }

        json.setPlanId(planId);
        String data = JSON.toJSONString(json);
        //新增或修改
        this.saveOrUpdate(userId, data);
//        Map<String, Object> seeByPlanIdId = this.findSeeByPlanId(planId);
//        System.out.println("查询结果个人计划对应的数据 "+seeByPlanIdId);
//
//
//        JSONObject jsonObject = JSON.parseObject(data);
//        String nomtimes = (String) jsonObject.get("nomtime");
//
//        Timer timer=new Timer();
//        TimerTask task=new TimerTask() {
//            @Override
//            public void run() {
//                System.out.println("开始时间是："+nomtimes);
//                Map<String, Object> message =seeByPlanIdId;
//                setTopicTitle(message);
//            }
//        };
        return ResponseInfo.success();
    }

    /**
     * 新增更新配置
     *
     * @param userId
     * @param data
     */
    public void saveOrUpdate(String userId, String data) {
        QueryWrapper qw = new QueryWrapper<PersonConfigTitle>();
        JSONObject jsonObject = JSON.parseObject(data);
        String planId = (String) jsonObject.get("planId");

        if (StringUtils.isNotEmpty(planId)) {
            qw.eq("plan_id", planId);
        }

        List<PersonConfigTitle> list = this.list(qw);

        if (list.size() == 0) {//新增
            PersonConfigTitle config = new PersonConfigTitle();
            config.setId(SysUtil.UUID());
            if (StringUtils.isNotEmpty(userId)) {
                config.setUserId(userId);
            }
            config.setPlanId(planId);
            config.setData(data);
            this.save(config);
        } else {
            UpdateWrapper<PersonConfigTitle> uw = new UpdateWrapper<>();
            //更新
            PersonConfigTitle config = list.get(0);
            uw.eq("id", config.getId());
            config.setPlanId(planId);
            uw.set("read_", "0");
            uw.set("data", data);
            this.update(uw);
//            System.out.println("修改");
        }

//            // 查询user_id对应的数据
//        System.out.println("------------"+userId);
//        List<PersonConfigTitle> departList = this.findSeeByUserId(planId);
//        System.out.println( departList);
    }

    /**
     * 返回给定时器的数据
     */
    @Override
    public Map IsTime() {
        String userId = SysUtil.getLoginUserId(request);
        UpdateWrapper<PersonConfigTitle> uw = new UpdateWrapper<>();
        uw.eq("user_id", userId);
        uw.eq("read_", "0");
        List<PersonConfigTitle> list = this.list(uw);

        // 检查列表是否为空
        if (list != null && !list.isEmpty()) {
            // 列表不为空，获取第一个元素的数据并解析JSON
            JSONObject jsonObject = JSON.parseObject(list.get(0).getData());
            String nomtime = (String) jsonObject.get("nomtime");
            Integer time = (Integer) jsonObject.get("time");
            String planId = (String) jsonObject.get("planId");
            // 解析 nomtime 字符串为 Date 对象
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date nomtimeDate;
            try {
                nomtimeDate = sdf.parse(nomtime);
            } catch (ParseException e) {
                return null;
            }
            // 获取当前时间
            Date currentTime = new Date();
            // 计算未来的时间点
            long futureTimeMillis = nomtimeDate.getTime() + (long) time * 1000; // 将秒转换为毫秒
            Date futureTime = new Date(futureTimeMillis);
            // 判断时间是否到达
            if (currentTime.after(futureTime)) {
                // 时间到了或正好到达
                Map<String, Object> seeByPlanIdId = this.findSeeByPlanId(planId);

                return ResponseInfo.success(seeByPlanIdId);
            } else {

                return null;
            }
        } else {

            return null;
        }
    }

    /**
     * 是否忽略未读信息
     */
    @Override
    public Map IsRead(String userId, Boolean open, Integer time, LocalDateTime nomtime, String planId, String read) {

        UpdateWrapper<PersonConfigTitle> uw = new UpdateWrapper<>();
        uw.eq("plan_id", planId);
        uw.set("read_", read);
        this.update(uw);

        return ResponseInfo.success();
    }


    /**
     * 查询planId对应的数据
     *
     * @param planId
     * @return
     */
    @Override
    public Map<String, Object> findSeeByPlanId(String planId) {
        return baseMapper.findSeeByPlanId(planId);
    }

    @Override
    public Map isIgnore(String planId) {
        QueryWrapper<PersonConfigTitle> qw = new QueryWrapper<>();
        qw.eq("plan_id", planId);
        List<PersonConfigTitle> list = this.list(qw);
        if (list != null && !list.isEmpty()) {
            PersonConfigTitle personConfigTitle = list.get(0);
            JSONObject jsonObject = JSON.parseObject(personConfigTitle.getData());
            jsonObject.put("nomtime", new DateEasy().toYYYYhMMhDDhHHcMMcSS());
            personConfigTitle.setData(jsonObject.toJSONString());
            this.updateById(personConfigTitle);
        }
        return ResponseInfo.success();
    }

    /**
     * 获取用户id
     *
     * @param userId
     * @return
     */
    public String getUserId(String userId) {
        if (StringUtils.isEmpty(userId)) {
            userId = SysUtil.getLoginUserId(request);
        }
        return userId;
    }

}
